<?php

namespace Cron;

use Lib\Queue;

class Sms extends \Cron\CronAbstract {

    protected $config    = null;

    public function main() {
        $config = $this->getConfig()->get('resources.sms');

        if(!$config instanceof \Yaf\Config\Ini) {
            return false;
        }

        $this->config = $config;

        $beginTime = time();

        while (time() - $beginTime < 59) {
            $sms = Queue::pop('sms');

            if (empty($sms)) {
                sleep(1);
                continue;
            }

            $this->send($sms);
        }
    }

    /**
     *  发送
     *
     * @param array $content
     * @param \Lib\Http $http
     * @return boolean
     */
    protected function send(array $content) {
        $http = new \Lib\Http();
        $time = date('YmdHis');
        $http->setTimeout(3);

        $config        = $this->config;
        $accountId     = $config->get('account_id');
        $accountToken  = $config->get('account_token');
        $baseURL       = $config->get('base_url');
        $sigParam      = strtoupper(md5($accountId . $accountToken . $time));
        $baseURI       = sprintf($config->get('uri'), $accountId, $sigParam);
        $authorization = base64_encode($accountId . ':' . $time);

        $content = $this->parseContent($content);
        $content['appId']      = $config->get('appid');
        $content['templateId'] = $config->get('template_id');

        $sendContent = \json_encode($content);

        $http->setHeader([
            'Accept:application/json',
            'Content-Type:application/json;charset=utf-8',
            'Content-Length:' . strlen($sendContent),
            'Authorization:' . $authorization
        ]);

        $http->setPostFields($sendContent);
        $http->setUrl($baseURL . $baseURI);

        try {
            $response = $http->send();
        } catch (\Exception $e) {
        }
    }

    /**
     * 解析内容
     *
     * @param array  $content
     * @return json
     */
    protected function parseContent(array $content) {
        $data = [];

        $data['to']    = isset($content['mobile']) ? $content['mobile']: null;
        $data['datas'] = isset($content['content']) ? [$content['content'], 15]: [];

        return $data;
    }
}
